package com.cnbot.canapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dc.android_can.CAN;
import com.dc.android_can.can.CanDataType;
import com.dc.android_can.can.CanUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private TextView sendCountTv;
    private TextView receiveCountTv;
    private EditText sendNumEt;
    private EditText sendIntervalEt;
    private Button initDeviceBtn;
    private Button   sendDataBtn;
    private Button   sendThreadBtn;
    private Button   receiveThreadBtn;
    private LinearLayout sendDataLl;

    private int appSendCount = 10;  //发送1w数据
    private int appSendTotol = 0;   //
    private int receiveCount = 0;  // 统计接收数据总数
    private int sendThreadInterval = 10;

    private boolean isSendThread = false;
    private boolean isReceiveThread = false;

    private List<File> fileList = new ArrayList<>();
    private SendThread sendThread;
    private ReceiveThread receiveThread;

    private ActHandler actHandler = null;
    private static final int HANDLER_SEND_COUNT = 0x01;
    private static final int HANDLER_RECEIVE_COUNT = 0X02;

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_init_device:
                initDevice();
                break;
            case R.id.btn_send_thread:
                new SendThread().start();
                break;
            case R.id.btn_receive_thread:
                new ReceiveThread().start();
                break;
        }
    }

    private class ActHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HANDLER_RECEIVE_COUNT:
                    sendCountTv.setText("共发送" + appSendTotol + "条数据");
                    break;
                case HANDLER_SEND_COUNT:
                    receiveCountTv.setText("共接收到" + receiveCount + "条数据");
                    break;
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

    }

    private void initView(){
        sendCountTv = (TextView) findViewById(R.id.tv_send_datacount);
        receiveCountTv = (TextView) findViewById(R.id.tv_receive_datacount);
        sendNumEt = (EditText) findViewById(R.id.et_send_num);
        sendIntervalEt = (EditText) findViewById(R.id.et_send_interval_time);
        initDeviceBtn = (Button) findViewById(R.id.btn_init_device);
        sendDataBtn = (Button) findViewById(R.id.btn_send_data);
        sendThreadBtn = (Button) findViewById(R.id.btn_send_thread);
        receiveThreadBtn = (Button) findViewById(R.id.btn_receive_thread);
        sendDataLl = (LinearLayout) findViewById(R.id.ll_send_data);

        initDeviceBtn.setOnClickListener(this);
        sendDataBtn.setOnClickListener(this);
        sendThreadBtn.setOnClickListener(this);
        receiveThreadBtn.setOnClickListener(this);
    }

    /**
     * @descriptoin	设备初始化
     * @author	dc
     * @date 2018/6/1 16:28
     */
    private void initDevice(){
        actHandler = new ActHandler();
        File spidev = new File("/dev/spidev0.0");
        File spiDevice = new File("/dev/SPI_INTERRUPT_AND_CS_CONTROL");
        fileList.add(spidev);
        fileList.add(spiDevice);
        for (File device : fileList) {
            /* Check access permission */
//            if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
                su = Runtime.getRuntime().exec("/system/xbin/su");
                String cmd = "chmod 6666 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead()
                        || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                //throw new SecurityException();
            }
        }
        int initResult = CAN.init();
        Log.e(TAG, "初始化 = " + initResult);
        Toast.makeText(MainActivity.this, "初始化 = " + initResult, Toast.LENGTH_SHORT).show();
    }



    /**
     * @descriptoin	数据接收线程
     * @author	dc
     * @date 2018/6/1 15:44
     */
    public class ReceiveThread extends Thread{
        @Override
        public void run() {
            while (!isReceiveThread){
                try {

                    CanDataType canDataType = CAN.ReadConDataType();
                    if(canDataType != null){
                        receiveCount++;
                            Log.e(TAG, "id = " + canDataType.id  +  "   len = " + canDataType.len+
                                    "   cmdWord = " + canDataType.cmdWord + "   buf = " + canDataType.buf[0]);
//                        Log.e("MainActivity", "接收总数 = " + receiveCount);
//                        Log.e("MainActivity", "canDataType = " + canDataType);
                        actHandler.sendEmptyMessage(HANDLER_SEND_COUNT);
                    }
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @descriptoin	数据发送线程
     * @author	dc
     * @date 2018/6/1 15:45
     */
    public class SendThread extends Thread{
        @Override
        public void run() {
            while (!isSendThread){
                if(appSendTotol < appSendCount){
                    appSendTotol++;
//                    byte[] buf = {0x08, 0x02, 0x20,0x00, 0x01, 0x02, 0x03, 0x04}; //, 0x04,0x05, 0x06, 0x07
                    byte[] bpByte = {0x04 ,0x02,  0x16 ,(byte)0x01};
                    int device = CanUtils.canWrite( bpByte    , 0);
                    Log.e("MainActivity", "发送总数 = " + appSendTotol);
                    actHandler.sendEmptyMessage(HANDLER_RECEIVE_COUNT);
                    try {
                        Thread.sleep(sendThreadInterval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isReceiveThread = true;
        isSendThread = true;

        if(sendThread != null){
            sendThread.interrupt();
            sendThread = null;
        }
        if(receiveThread != null){
            receiveThread.interrupt();
            receiveThread = null;
        }
    }
}
